package svnserver.service;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.redisson.Redisson;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;

public class Resque {
  private static RedissonClient redisson = null;
  private static RList<String> rList = null;
  private static RList<String> rBackup = null;
  private static RList<String> rSizeLits = null;
  protected final static ObjectMapper mapper = new ObjectMapper(); /// We known jackson ObjectMapper is Thread safe

  public static RedissonClient getRedisson() {
    return redisson;
  }

  public static boolean RedissonInitialize(@NotNull String address) {
    Config config = new Config();
    config.setCodec(StringCodec.INSTANCE);
    config.useSingleServer().setAddress(address);
    redisson = Redisson.create(config);
    if (redisson == null)
      return false;
    rList = redisson.getList("resque:gitlab:queue:post_receive");
    if (rList == null) {
      System.out.printf("resque:gitlab:queue:post_receive null");
      return false;
    }
    rBackup = redisson.getList("gitee:queue:repo:backup");
    if (rBackup == null) {
      System.out.printf("gitee:queue:repo:backup null");
      return false;
    }
    if (Parameters.Get().EnableSizeEvent()) {
      rSizeLits = redisson.getList("gitee.queue.size:event");
      if (rSizeLits == null) {
        System.out.printf("gitee.queue.size:event null");
        return false;
      }
    }
    return true;
  }

  public static boolean ResqueInsert(@NotNull String pwn, @NotNull String refname, @Nullable String oldrev,
      @NotNull String newrev, long uid) {
    String oldrev2 = oldrev == null ? "0000000000000000000000000000000000000000" : oldrev;
    String m = String.format("{\"class\":\"PostReceive\",\"args\":[\"%s\",\"%s\",\"%s\",\"%s\",\"user-%d\"]}", pwn,
        oldrev2, newrev, refname, uid);
    return rList.add(m);
  }

  // SubversionBackup backup
  public static boolean SubversionBackup(@NotNull String pwn, boolean syncuuid) {
    try {
      BackupContext bc = new BackupContext(pwn, syncuuid);
      String rbody = mapper.writeValueAsString(bc);
      return rBackup.add(rbody);
    } catch (Exception e) {
      return false;
    }
  }

  public static boolean SubversionSizeEvent(@NotNull String dir, @NotNull String pwn) {
    if (rSizeLits == null) {
      return false;
    }
    try {
      SizeEventContext sc = new SizeEventContext(dir, pwn, -1);
      String rbody = mapper.writeValueAsString(sc);
      return rBackup.add(rbody);
    } catch (Exception e) {
      return false;
    }
  }
}
